package game.module.club.dao;

import java.io.File;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.Files;

import game.module.template.ClubUpTemplate;
import lion.common.Reloadable;

/**
 * @author: Pomelo.Lee
 * @date: 2017年8月29日 上午10:37:26
 */
public class ClubUpTemplateCache implements Reloadable {

	private static Logger logger = LoggerFactory.getLogger(ClubUpTemplateCache.class);

	static class SingletonHolder {
		static ClubUpTemplateCache instance = new ClubUpTemplateCache();
	}

	public static ClubUpTemplateCache getInstance() {
		return SingletonHolder.instance;
	}

	private transient List<ClubUpTemplate> templateList;

	private transient Map<Integer, ClubUpTemplate> map_templateList;

	@Override
	public void reload() {

		try {
			String jsonStr = Files.asCharSource(new File("data/clubup.json"), Charset.forName("UTF-8")).read();
			ObjectMapper mapper = new ObjectMapper();
			templateList = mapper.readValue(jsonStr, new TypeReference<List<ClubUpTemplate>>() {
			});
			Map<Integer, ClubUpTemplate> tmpmap = new ConcurrentHashMap<>();
			for (ClubUpTemplate template : templateList) {
				tmpmap.put(template.getLevel(), template);
			}
			map_templateList = tmpmap;
			logger.info("size={}", templateList.size());
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	public ClubUpTemplate getTemplate(int level) {
		return (map_templateList.get(level));

	}

	public static void main(String[] args) {
		ClubUpTemplateCache ctc = ClubUpTemplateCache.getInstance();
		ctc.reload();

		for (ClubUpTemplate ct : ctc.templateList) {
			System.out.println(ct.getLevel());
		}
	}

}
